package C051;

import java.util.Arrays;

/**
 * ClassName: C04
 * Package: C051
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/3/10 10:10
 * @Version 1.0
 * @Since 1.0
 */
public class C04 {
    public static void main(String[] args) {
        int[] arr = {1,3,1};
        System.out.println(smallestDistancePair(arr, 1));
    }

    public static int smallestDistancePair(int[] nums, int k) {
        Arrays.sort(nums);

        int l = 0 , r = nums[nums.length - 1] - nums[0], mid;
        int ans = -1;
        while (l <= r) {
            mid = l + ((r - l) >> 1);
            int count = process(nums, mid);
            if (count >= k) {
                r = mid - 1;
                ans = mid;
            } else if (count < k) {
                l = mid + 1;
            }
        }

        return ans;
    }

    // nums中，小于mid 的数对的数量
    private static int process(int[] nums, int mid) {
        int res = 0;
        for (int l = 0, r = 0; l < nums.length; l++) {
            while(r + 1 < nums.length && nums[r + 1] - nums[l] <= mid) {
                r ++;
            }
            res += r - l;
        }
        return res;
    }
}
